# Copyright 2009 http://www.yuntien.com
# Licensed under the Apache License, Version 2.0

from google.appengine.api import users
from authorization_def import *
import ytblog.config

def get_role(obj=None):
  if users.is_current_user_admin():
    return ROLE_ADMIN
  
  if users.get_current_user():
    # TODO: need to ensure that obj has an author property
    if obj is not None and users.get_current_user() == obj.author:
      return ROLE_OWNER
    return ROLE_USER
  
  return ROLE_GUEST

def comp_role(role1, role2):
  rating = {
    ROLE_ADMIN    : 9,
    ROLE_OWNER    : 8,
    ROLE_USER     : 7,
    ROLE_GUEST    : 0,
    }

  return rating[role1] > rating[role2]

def get_auth(obj):
  # cls should be a subclass of db.Model
  cls, obj = obj
  role = get_role(obj)
  
  while obj is not None and obj.get_parent() is not None:
    obj = obj.get_parent()
    role_tmp = get_role(obj)
    if comp_role(role_tmp, role):
      role = role_tmp    
  
  return AUTH_MODEL[cls.kind()][role]
